package com.opesoft.fw.i18n.taglib;

import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
import org.apache.log4j.Logger;

import com.opesoft.fw.core.Constants;
import com.opesoft.fw.core.utils.WebUtils;
import com.opesoft.fw.i18n.I18nBO;
import com.opesoft.fw.i18n.Messages;

public class Init extends TagSupport
{
	Logger log=Logger.getLogger(this.getClass());

	protected String uri;
	protected String prefix;

	@SuppressWarnings("unchecked")
	@Override
	public int doEndTag() throws JspException
	{
		if(this.uri!=null&&!"".equals(this.uri))
		{
			if("".equals(this.prefix)) this.prefix=null; // 前缀为null为默认值
			HttpServletRequest request=(HttpServletRequest)this.pageContext.getRequest();

			// 如果是相对路径，变换为绝对路径
			if(!this.uri.startsWith("/"))
			{
				String path=WebUtils.subContextPath(this.pageContext,request.getRequestURI().toString());
				if(path.indexOf("/")>-1&&!path.endsWith("/")) path=path.substring(0,path.lastIndexOf("/"));
				if(!path.endsWith("/")) path+="/";
				this.uri=path+this.uri;
			}

			// 根据国际化配置文件，构造出一个Messages对象
			Messages msgs=I18nBO.createMessages(this.pageContext.getServletContext().getRealPath(this.uri));

			// 把Messages存入到PageContext中
			Map<String, Messages> msgsMap;
			if(pageContext.getAttribute(Constants.I18N_MESSAGES_MAP)==null) pageContext.setAttribute(Constants.I18N_MESSAGES_MAP,new HashMap<String, Messages>());
			msgsMap=(Map<String, Messages>)pageContext.getAttribute(Constants.I18N_MESSAGES_MAP);
			msgsMap.put(prefix,msgs);
		}

		this.uri=null;
		this.prefix=null;
		return super.doEndTag();
	}

	public String getPrefix()
	{
		return prefix;
	}

	public void setPrefix(String prefix)
	{
		this.prefix=prefix;
	}

	public String getUri()
	{
		return uri;
	}

	public void setUri(String uri)
	{
		this.uri=uri;
	}

}
